package com.yonyou.crm.csns.phonebook.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.csns.phonebook.entity.DeptListVO;
import com.yonyou.crm.csns.phonebook.entity.OrgVO;
import com.yonyou.crm.csns.phonebook.entity.PersonListVO;
import com.yonyou.crm.csns.phonebook.entity.PersonVO;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class OrgBizServiceImpl extends BaseBizServiceImpl<OrgVO> {

	@Autowired
	private SysOrgBizServiceImpl sysOrgService;
	
	@Autowired
	private PersonBizServiceImpl personService;

	public List<DeptListVO> getMyDeptList() {
		
		String deptIdStr = (String)InvocationInfoProxy.getParameter("deptid");//所属部门
		Long deptId = Long.parseLong(deptIdStr);
		
		OrgVO mydept = dao.getById(OrgVO.class, deptId);

		List<DeptListVO> list = new ArrayList<DeptListVO>();
		if (mydept == null) {
			return list;
		}
		
		DeptListVO vo = new DeptListVO();
		vo.setId(deptId);
		vo.setName(mydept.getName());
		vo.setFlag("my");
		vo.setNum(mydept.getNum());
		vo.setPic(mydept.getPic());
		
		list.add(vo);
		return list;
	}
	
	public List<DeptListVO> getDeptList(Map<String, Object> paraMap) {
		List<OrgVO> orgList = dao.selectVoList(OrgVO.class, "getChildren", paraMap);
		List<DeptListVO> rsList = new ArrayList<DeptListVO>();
		
		for (OrgVO vo : orgList) {
			DeptListVO listVO = new DeptListVO();
			listVO.setId(vo.getId());
			listVO.setName(vo.getName());
			listVO.setPic(vo.getPic());
			listVO.setFlag("");
			listVO.setNum(vo.getNum());
			
			rsList.add(listVO);
		}
		return rsList;
	}
	
	public Map<String, Object> getOrganization(Long deptId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<DeptListVO> myDeptList = getMyDeptList();
		map.put("mydeptlist", myDeptList);

		if (deptId == null) {
			deptId = 0L;
		}
		
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("tenantId", tenantId);
		paraMap.put("orgId", orgId);
		paraMap.put("deptId", deptId);
		
		List<DeptListVO> deptList = getDeptList(paraMap);
		map.put("deptlist", deptList);
		
		if (deptId.equals(0L)) {
			paraMap.remove("deptId");
			paraMap.put("deptId", orgId);
		}
		List<PersonListVO> personList = personService.getChildrenPersonList(paraMap);
		map.put("personlist", personList);
		
		return map;
	}
	
	public Map<String, Integer> countOneByDeptIds() {
		List<Map<String, Object>> orgIds = dao.selectList(OrgVO.class, "getOrgIds");
		Integer num = 0;
		
	    Map<String, Integer> rsMap = new HashMap<String, Integer>();
		for (Map<String, Object> orgIdMap : orgIds) {
			Long orgId = Long.parseLong(orgIdMap.get("orgId").toString());
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("deptId", orgId);
			num = dao.countAll(PersonVO.class, "countByDeptId", paraMap);
			
			rsMap.put(orgId.toString(), num);
		}
		
		return rsMap;
	}
	
	public Map<String, Integer> countAllByDeptId() {
		Map<String, Integer> numMap = countOneByDeptIds();
		
		List<Map<String, Object>> orgTree = sysOrgService.getSysOrgTree();
		Map<String, Integer> numsMap =  getSubOrgIds(numMap, orgTree);
		
		String[] keys = numsMap.keySet().toArray(new String[0]);
		Integer[] nums = numsMap.values().toArray(new Integer[0]);
		for (int i=0; i<keys.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orgId",keys[i]);
			map.put("num", nums[i]);
			dao.updateSql(OrgVO.class, "savePersonNum", map);
		}
		
		return numsMap;
	}
	
	//算错了
	private Map<String, Integer> getSubOrgIds(Map<String, Integer> numMap, List<Map<String, Object>> orgTree) {
		
		for (Map<String, Object> m : orgTree) {
			String key = m.get("id").toString();
			
			List children = (List)m.get("children");
			if (!children.isEmpty()) {
				numMap = getSubOrgIds(numMap, children);
			}
			String parentKey = m.get("fatherorg_id").toString();
			Integer parentNum = 0;
			if (numMap.containsKey(parentKey)) {
				parentNum = numMap.get(parentKey);
			}
			if (numMap.containsKey(key)) {
				numMap.put(parentKey, parentNum + numMap.get(key));
			}
			
		}
		return numMap;
	}
	
	/*
	 * 根据deptId取部门及下级部门和下级人员树，当deptId为空时，取当前操作人所在部门
	 */
	public List<Map<String, Object>> getDeptWithSub(Long deptId) {
		List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
		if (deptId == null || deptId.equals(0L)) {
			String deptIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.DeptId);
			if (deptIdStr == null || deptIdStr.isEmpty()) {
				return rsList;
			}
			deptId = Long.parseLong(deptIdStr);
		}
		return getSubDeptsAndUsers(deptId);
	}
	
	/*
	 * 获取集团组织架构
	 */
	public List<Map<String, Object>> getOrgTree() {
		return getSubDeptsAndUsers(null);
	}
	
	/*
	 * 获取子部门树(含部门人员)
	 */
	private List<Map<String, Object>> getSubDeptsAndUsers(Long deptId) {
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", InvocationInfoProxy.getTenantid());
		if (deptId != null && !deptId.equals(0L)) {
			param.put("deptId", deptId);
		}
		
		List<Map<String, Object>> list = dao.selectList(OrgVO.class, "findSysOrgTree", param);
		
		return list;
	}
	
	/*
	 * 通讯录搜索，关键字可以是部门名称或者人员姓名，结果包含部门列表和人员列表
	 */
	public Map<String, Object> searchList(String searchKey) {
		List<Map<String, Object>> deptList = getDeptsByName(searchKey);
		List<Map<String, Object>> userList = personService.getUsersByName(searchKey);

		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("orgList", deptList);
		rsMap.put("userList", userList);
		return rsMap;
	}
	
	/*
	 * 按名称搜索部门 
	 */
	public List<Map<String, Object>> getDeptsByName(String searchKey) {
		String tenantIdStr = InvocationInfoProxy.getTenantid();
		Long tenantId = Long.parseLong(tenantIdStr);
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("searchKey", searchKey);
		paraMap.put("tenantId", tenantId);
		
		List<Map<String, Object>> list = dao.selectList(OrgVO.class, "getList", paraMap);
		return list;
	}
	
}
